package com.gr.gojcodesandbox.codesandbox.java;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.gr.gojcodesandbox.model.ExecuteMessage;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Java 代码沙箱模板方法的实现
 */
@Component
public class JavaDockerCodeSandbox extends JavaCodeSandBoxTemplate {

    private static final long TIME_OUT = 5000L;

    private static final String image = "openjdk:8-alpine";     // 使用的镜像

    /**
     * 3. 创建容器，把文件复制到容器内
     * @param userCodeFile
     * @param inputList
     * @return
     */
    @Override
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("unix:///var/run/docker.sock")
                .build();
        //获取 Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置字符串"));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStdin(true)
                .withAttachStderr(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        System.out.println(createContainerResponse);
        String containerId = createContainerResponse.getId();
        try {
            File tarFile = createTarArchive(userCodeFile.getAbsolutePath());
            dockerClient.copyArchiveToContainerCmd(containerId)
                    .withRemotePath("/code") // 判题容器中的路径
                    .withTarInputStream(new FileInputStream(tarFile))
                    .exec();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        // docker exec elastic_wilson java -cp /app Main 1 3
        // 执行命令并获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {

            try {
                Files.write(
                        Paths.get(userCodeParentPath + File.separator + "input.txt"),
                        Collections.singletonList(inputArgs), // 也可以传 List<String>
                        StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING // 如果文件已存在则覆盖
                );
                File tarFile = createTarArchive(userCodeParentPath + File.separator + "input.txt");
                dockerClient.copyArchiveToContainerCmd(containerId)
                        .withRemotePath("/code") // 判题容器中的路径
                        .withTarInputStream(new FileInputStream(tarFile))
                        .exec();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            StopWatch stopWatch = new StopWatch();
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd("sh", "-c", "javac /code/Main.java && java -cp /code Main < /code/input.txt")
                    .withUser("0")  // 用 root 用户运行命令，解决写文件/权限问题
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            long time = 0L;
            // 用于判断是否超时
            final boolean[] timeout = {true};
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    // 如果执行完成，则表示没超时
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };

            final long[] maxMemory = {0L};

            // 获取占用内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            };
            statsCmd.exec(statisticsResultCallback);
            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        dockerClient.removeContainerCmd(containerId).withForce(true).exec();
        return executeMessageList;
    }

    private static File createTarArchive(String filePath) throws IOException {
        File file = new File(filePath);
        File tarFile = new File(file.getParent(), "archive.tar");

        try (TarArchiveOutputStream out = new TarArchiveOutputStream(new FileOutputStream(tarFile))) {
            out.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
            TarArchiveEntry entry = new TarArchiveEntry(file, file.getName());
            entry.setSize(file.length());
            out.putArchiveEntry(entry);
            Files.copy(file.toPath(), out);
            out.closeArchiveEntry();
        }

        return tarFile;
    }

}
